﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using twittershared;
//using ServiceStack.Text;
using ServiceStack.Text.Jsv;
namespace botfollow
{
    
    public class followlogrecord
    {
        public DateTime time { get; set; }
        public string user { get; set; }

        
    }
    class Program
    {
        static void Main(string[] args)
        {
            loadFriendsLog();
        




            double slotsPerDay = 1000;
            double secondsPerSlot = (24*60*60)/slotsPerDay;
            
            string scurday = DateTime.Now.ToShortDateString();
            bool cont = true;
            DateTime lastTwitterOp = DateTime.Now; ;
            while (cont)
            {
                double secondsFromTheDayBegining = DateTime.Now.Hour * 60*60 + DateTime.Now.Minute*60+DateTime.Now.Second;
                double curslot = (secondsFromTheDayBegining / secondsPerSlot);
                log(string.Format("[{2} {0}/{1}]", (int)curslot, (int)slotsPerDay, scurday));
                doslotwork();
                lastTwitterOp = DateTime.Now;

                if ((DateTime.Now - lastTwitterOp).TotalSeconds < secondsPerSlot)
                {
                    log("sleep");
                    int sleepTime = (int)(secondsPerSlot * 1000 + 100);
                    
                    System.Threading.Thread.Sleep(sleepTime);
                    log("wake up");

                }

            }

        //log file
         //   log();
        }
        static string getbestdesination(List<string> excluded)
        {
            return "1";
        }
        static List<followlogrecord> friendingLog;
        private const string friendingLogName = "../db/friends.log";
        static void loadFriendsLog()
        {
            
            if( System.IO.File.Exists(friendingLogName))
            {
                string sfile = System.IO.File.ReadAllText(friendingLogName);
                friendingLog = ServiceStack.Text.TypeSerializer.DeserializeFromString<List<followlogrecord>>(sfile);
            }
            else
            {
                friendingLog=new List<followlogrecord>();
            }
        }
        static void saveFriendsLog()
        {
            string sbody = ServiceStack.Text.TypeSerializer.SerializeToString<List<followlogrecord>>(friendingLog);
            System.IO.File.WriteAllText(friendingLogName,sbody);
        }

        static void log(string mes)
        {
            string time = DateTime.Now.ToLongTimeString();
            Console.WriteLine(time+" "+mes);
        }
        static List<string> excludedusers = new List<string>();
        static void doslotwork()
        {
            //загружаем все твиты


            string bestdestination = "";
            //находим с лучшим rank'ом
            bool founded = false;
            for (;;)
            {
                founded = false;
                bestdestination = getbestdesination(excludedusers);
                //
                log("best rank: " + bestdestination);
                //этот адресат уже друг
                bool allreadyFriend = friendingLog.Exists(r => r.user == bestdestination);
                if (allreadyFriend)
                {
                    log("allready spammed");
                    excludedusers.Add(bestdestination);
                    continue;
                }
                if (isfriend(bestdestination))
                {
                    log("allready followed");
                    excludedusers.Add(bestdestination);
                    continue;
                }
                //этот адресат уже может быть folloup ен ранее
                

                

                founded = true;
                break;
            }

            if (founded)
            {
              //  follow(bestdestination);
                var rec = new followlogrecord()
                {
                    time = DateTime.Now,
                    user = bestdestination
                };
                friendingLog.Add(rec);
                saveFriendsLog();
            }
           


        }
    
       

        static void useaccount(string username)
        {
            keys.screenName = username;
            keys.token = System.Configuration.ConfigurationSettings.AppSettings["token-" + username];
            keys.tokenSecret = System.Configuration.ConfigurationSettings.AppSettings["tokenSecret-" + username];
        }
        static void unfollow(string username)
        {
            var rparams = new Dictionary<string, string>();
            rparams.Clear();
            rparams.Add("id", username);

            var doc = xmltwitapi("friendships/destroy.xml", rparams, false);


        }

        static bool isfriend(string username)
        {
            var rparams = new Dictionary<string, string>();
            rparams.Add("user_b", username);
            rparams.Add("user_a", keys.screenName);

            var doc = xmltwitapi("friendships/exists.xml", rparams, true);

            bool alreadyFriends = bool.Parse(doc.DocumentElement.InnerText);
            return alreadyFriends;

        }

        static void follow(string username)
        {
            var rparams = new Dictionary<string, string>();
            rparams.Add("user_b", username);
            rparams.Add("user_a", keys.screenName);



            if (isfriend(username))
            {
                unfollow(username);
            }


            rparams.Clear();
            rparams.Add("id", username);

            XmlDocument doc = xmltwitapi("friendships/create.xml", rparams, false);

        }

        static XmlDocument xmltwitapi(string url, Dictionary<string, string> rparams, bool useget)
        {
            string followResp = twitapi(url, rparams, useget);
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(followResp);
            return doc;
        }
        static string twitapi(string url, Dictionary<string, string> rparams, bool useget)
        {
            DateTime dt1 = DateTime.Now;

            string logpars = "";
            if (rparams.Count > 0)
            {
                logpars = " " + rparams.Keys.ToArray()[0] + "=" + rparams.Values.ToArray()[0];
            }
            log(url + " " + logpars);
            try
            {
                Twitterizer.HTTPVerb verb = Twitterizer.HTTPVerb.POST;
                if (useget)
                    verb = Twitterizer.HTTPVerb.GET;

                string baseurl = "http://api.twitter.com/1/";
                var resp = Twitterizer.OAuthUtility.BuildOAuthRequestAndGetResponse(baseurl + url, rparams,
                     verb,
                     keys.consumerKey, keys.consumerSecret,
                     keys.token, keys.tokenSecret);
                string followResp = Twitterizer.OAuthUtility.getAnswer(resp);
                return followResp;
            }
            finally
            {
                DateTime dt2 = DateTime.Now;
                string stime = (dt2 - dt1).TotalMilliseconds.ToString() + "ms";
                log("        " + stime);
            }
        }
        
    }
}
